package com.hw.servlet;

import com.hw.dao.CountriesDao;
import com.hw.entity.Countries;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.List;

@WebServlet(name = "GGServlet" ,urlPatterns = "/gt")
public class GGServlet extends HttpServlet {
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

         response.setCharacterEncoding("utf-8");
        CountriesDao countriesDao=new CountriesDao();
        List<Countries> countries=countriesDao.findAll();
        StringBuffer json=new StringBuffer("{\"code\":200,\"data\":[");
        for (Countries c:countries){
            json.append("{\"countryId\":\"")
                    .append(c.getCountryId())
                    .append("\",")
                    .append("\"countryName\":\"")
                    .append(c.getCountryName())
                    .append("\",")
                    .append("\"regionId\":")
                    .append(c.getRegionId())
                    .append("},");
        }
        json.deleteCharAt(json.length()-1);
        json.append("]}");

      /*  StringBuffer head=new StringBuffer("{'code':200,'data':");*/
/*
        String json=countries.toString().replaceAll("Countries"," ").replaceAll("=",":");
*/
        String json1="[ {'countryId':'AR', 'countryName':'Argentina', 'regionId':2},  {'countryId':'AU', 'countryName':'Australia', 'regionId':3}]";
       /* head.append(json1).append("}");*/
        response.setContentType("application/json;utf-8");
        PrintWriter out=response.getWriter();
        out.write(json.toString());
        /*out.print(head.toString());*/
    }
}
